package com.bianmaba.remote.supports;

import com.bianmaba.commons.bean.result.OperationResult;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Log4j2
public abstract class BaseRemoteRequestService implements IBaseRemoteRequestService {
    @Autowired
    protected RestTemplate restTemplate;
    protected Map<Integer, String> CODE_ERROR_MAPPING = new HashMap() {{
        put(401, "远程请求失败，请求地址未经授权访问或由于凭据无效被拒绝：");
        put(403, "远程请求失败，请求地址未经授权访问或由于凭据无效被拒绝：");
        put(404, "远程请求失败，请求地址未经授权访问或由于凭据无效被拒绝：");
        put(405, "远程请求失败，请求地址未经授权访问或由于凭据无效被拒绝：");
        put(500, "远程请求失败，请求地址未经授权访问或由于凭据无效被拒绝：");
    }};

    @Override
    public <T> ResponseEntity<T> postForEntity(String url, HttpEntity entity, Class<T> clazz) {
        ResponseEntity<T> responseEntity = restTemplate.postForEntity(url, entity, clazz);
        return responseEntity;
    }

    public OperationResult handleException(String url, String parameters, Exception ex) {
        if (ex instanceof HttpClientErrorException) {
            HttpClientErrorException e = (HttpClientErrorException) ex;
            int code = e.getRawStatusCode();
            String error = CODE_ERROR_MAPPING.get(e.getRawStatusCode());
            if (error == null) {
                error = String.format("远程请求（%s）错误：", code);
            }
            error = error + String.format("【statusCode=%d,URL=%s,parameters=%s】", code, url, parameters);
            log.error(error, e);
            return OperationResult.of(false).setResult(error).setException(e);
        } else if (ex instanceof ResourceAccessException) {
            ResourceAccessException e = (ResourceAccessException) ex;
            String error = String.format("远程请求失败，服务器未开启，请联系管理员：【URL=%s,parameters=%s】", url, parameters);
            log.error(error, e);
            return OperationResult.of(false).setResult(error).setException(e);
        } else {
            String error = String.format("远程请求出现未知异常，请联系管理员：【URL=%s,parameters=%s】", url, parameters);
            log.error(error, ex);
            return OperationResult.of(false).setResult(error).setException(ex);
        }
    }
}
